package com.thingple.usb.session;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;

public abstract class SerialSession extends SessionThread {

    protected int baudRate;

    public SerialSession(UsbManager usbManager, UsbAccessory device, int baudRate) {
        this.usbManager = usbManager;
        this.device = device;
        this.baudRate = baudRate;
    }

    public byte[] SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
        byte tmp = 0x00;
        byte[] payload = new byte[5];

        payload[0] = 0x30;
        payload[1] = SerialPortConfig.getBaudRate(baud);

        tmp = SerialPortConfig.getDataBits(dataBits);

        switch(stopBits){
            case 1:tmp &= ~(1 << 2);break;
            case 2:tmp |= (1 << 2);break;
            default:tmp &= ~(1 << 2);break; // default stop bit "1"
        }

        switch(parity){
            case 0:tmp &= ~( (1 << 3) | (1 << 4) | (1 << 5) );break; //none
            case 1:tmp |= (1 << 3);break; //odd
            case 2:tmp |= ( (1 << 3) | (1 << 4) );break; //event
            case 3:tmp |= ( (1 << 3) | (1 << 5) );break; //mark
            case 4:tmp |= ( (1 << 3) | (1 << 4) | (1 << 5) );break; //space
            default:tmp &= ~( (1 << 3) | (1 << 4) | (1 << 5));break;//default parity "NONE"
        }

        switch(flowControl){
            case 0:tmp &= ~(1 << 6);break;
            case 1:tmp |= (1 << 6);break;
            default:tmp &= ~(1 << 6);break; //default flowControl "NONE"
        }
        // dataBits, stopBits, parity, flowControl
        payload[2] = tmp;

        payload[3] = 0x00;
        payload[4] = 0x00;

        return payload;
    }
}
